﻿using DataWorks_IBLL;
using DataWorks_Sqlite.MappingClass;
using DataWorks_Tools.ProcessExcute.Merge;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
using System.Reflection;

namespace DataWorks_WebApi.Controllers
{
    [EnableCors("react")]
    [Route("[controller]/[action]")]
    [ApiController]
    public class DW_PropsMileageCombineController : ControllerBase
    {
        private readonly ILogger<DW_PropsMileageCombineController> _logger;
        private readonly IBLL_Props_MileageCombine  _bLL_Props_MileageCombine;
        private readonly IMemoryCache _memoryCache;//内存缓存
        private readonly IBLL_Props_Admin _bLL_Props_Admin;
        private readonly string controllerName;
        public DW_PropsMileageCombineController(ILogger<DW_PropsMileageCombineController> logger, IBLL_Props_MileageCombine bLL_Props_MileageCombine, IBLL_Props_Admin bLL_Props_Admin, IMemoryCache memoryCache)
        {
            _logger = logger;
            _bLL_Props_MileageCombine = bLL_Props_MileageCombine;
            _memoryCache = memoryCache;
            _bLL_Props_Admin = bLL_Props_Admin;
            controllerName = this.GetType().Name;
        }
        [HttpGet]
        public IActionResult GetPropsMileageCombine(int page, int pagesize, string loginname)
        {
            var data = _bLL_Props_MileageCombine.LoadEntities(a => a.loginname == loginname);
            var datacount = data.Count();
            var pagedata = data.Skip((page - 1) * pagesize).Take(pagesize).OrderBy(a => a.key);
            return Ok(new { pagedata, total = datacount });
        }

        [HttpPost]
        public IActionResult AddPropsMileageCombine([FromBody] dw_props_mileagecombine row)
        {
            //先按照key来排序获得最后一个数据
            var last = _bLL_Props_MileageCombine.LoadEntities(a => true).OrderBy(a => a.key).LastOrDefault();
            if (last != null)
            {
                //把要添加的数据的key改为最后一个数据的key+1，这样数据库里就是连续的数据，不会出现断档的key
                row.key = last.key + 1;
            }
            else
            {
                row.key = 1;
            }
            var isaddsucess = _bLL_Props_MileageCombine.AddEntity(row);
            var t = MethodBase.GetCurrentMethod();
            string? methodName = t?.Name;
            if (isaddsucess)
            {
                _logger.LogInformation($"{controllerName}控制器{methodName}方法,执行成功：{DateTime.Now}");

                return Ok("添加成功");
            }
            else
            {
                _logger.LogError($"{controllerName}控制器{methodName}方法,执行失败-数据库操作失败：{DateTime.Now}");

                return BadRequest("添加失败");
            }
        }


        [HttpPut]
        public IActionResult EditPropsMileageCombine([FromBody] dw_props_mileagecombine row)
        {
            var t = MethodBase.GetCurrentMethod();
            string? methodName = t?.Name;
            var iseditsucess = _bLL_Props_MileageCombine.EditEntity(row);

            if (iseditsucess)
            {
                _logger.LogInformation($"{controllerName}控制器{methodName}方法,执行成功：{DateTime.Now}");

                return Ok("编辑成功");
            }
            else
            {
                _logger.LogError($"{controllerName}控制器{methodName}方法,执行失败-数据库操作失败：{DateTime.Now}");

                return BadRequest("编辑失败");
            }
        }
        [HttpDelete]
        public IActionResult DelPropsMileageCombine(int key)
        {
            var t = MethodBase.GetCurrentMethod();
            string? methodName = t?.Name;
            var data = _bLL_Props_MileageCombine.LoadEntities(a => true).Where(a => a.key == key).FirstOrDefault();

            if (data != null)
            {
                var isdelsuccess = _bLL_Props_MileageCombine.DeleteEntity(data);
                if (isdelsuccess)
                {
                    _logger.LogInformation($"{controllerName}控制器{methodName}方法,参数为{key}执行成功：{DateTime.Now}");
                    return Ok("删除成功");
                }
                else
                {
                    _logger.LogError($"{controllerName}控制器{methodName}方法,参数为{key}执行失败：{DateTime.Now}");
                    return BadRequest("删除失败");

                }
            }
            else
            {
                _logger.LogError($"{controllerName}控制器{methodName}方法,参数为{key}执行失败-找不到数据：{DateTime.Now}");
                return BadRequest("无法删除");
            }

        }

        [HttpPost]
        public async Task<IActionResult> ExcuteDataMileageCombine(dw_props_mileagecombine row)
        {
            try
            {
                var adminprops = _memoryCache.GetOrCreate<dw_props_admin>("adminprops", value =>
                {
                    value.SlidingExpiration = TimeSpan.FromMinutes(10);
                    return _bLL_Props_Admin.LoadEntities(a => true).First();
                });
               
                 var t=await MileageMergeProcess.MileageMergeProcessExcute(adminprops, row);
                string result = string.Join(Environment.NewLine, t);
                _logger.LogWarning(result);
                return Ok(result);
            }
            catch (Exception ex)
            {
                var t = MethodBase.GetCurrentMethod();
                string? methodName = t?.Name;
                _logger.LogError($"{controllerName}控制器{methodName}方法,用户名为{row.loginname}执行失败，失败原因为{ex.Message}：{DateTime.Now}");
                throw;
            }

        }
    }
}
